package userHelp

import (
	"common/helper"
	myredis "common/redis"
	"context"
	"fmt"
	"strconv"
	"time"
)

/*
玩家日常行为记录
*/

const (
	Action_Register     = 0x000001 //注册
	Action_Login        = 0x000002 //登录
	Action_FirstDeposit = 0x000004 //首次充值
	Action_Deposit      = 0x000008 //充值
	Action_Withdraw     = 0x000010 //提款
	Action_Bet          = 0x000020 //投注
)

func AddUserDailyAction(uid string, Action int64) {
	if uid == "" {
		return
	}

	LoadUserToRedis(uid)

	//加锁 防止客户端在极短时间内发两次请求 会有异常日志
	lockKey := fmt.Sprintf("Action:%d", Action)
	if !myredis.Lock(myredis.GetRedisInstance(), uid+lockKey) {
		helper.InfoLog("AddUserDailyAction lock error")
		return
	}

	defer myredis.Unlock(myredis.GetRedisInstance(), uid+lockKey)

	redisKey := fmt.Sprintf("UserId:%s", uid)
	retValue, _ := myredis.GetRedisInstance().HGet(context.Background(), redisKey, "Daily_Action").Result()
	dailyAction, _ := (strconv.ParseInt(retValue, 10, 64))

	ActionTime, _ := myredis.GetRedisInstance().HGet(context.Background(), redisKey, "Daily_Action_Time").Result()

	//判断时间是否是当天
	TodayTimeFormat := time.Now().Format("2006-01-02")

	var redisValue string
	if ActionTime != TodayTimeFormat {
		dailyAction = 0
		redisValue = fmt.Sprintf("%d", dailyAction)
		myredis.GetRedisInstance().HSet(context.Background(), redisKey, "Daily_Action", redisValue)
		myredis.GetRedisInstance().HSet(context.Background(), redisKey, "Daily_Action_Time", TodayTimeFormat)
	}

	//说明此行为已经记录过
	if (dailyAction & Action) != 0 {
		return
	}

	dailyAction |= Action

	redisValue = fmt.Sprintf("%d", dailyAction)
	myredis.GetRedisInstance().HSet(context.Background(), redisKey, "Daily_Action", redisValue)

	_, errExec := g_sql.Exec("CALL tbl_report_user_daily_behavior(?,?,?)", uid, time.Now().Unix(), Action)
	if errExec != nil {
		helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_daily_behavior(%s,%d,%d);	reason:%s",
			uid, time.Now().Unix(), dailyAction, errExec.Error())
	}
	//else {
	//	helper.GetloggerInstance().Infof("[tbl_report_user_daily_behavior] param:%s---%d---%d",
	//		uid, time.Now().Unix(), dailyAction)
	//}
}
